package com.bookstore.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookstore.back.entity.BookTag;
import com.bookstore.back.mapper.BookTagMapper;
import com.bookstore.back.service.TagService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 图书标签服务实现类
 * 
 * @author 程序猿_Ti
 * @since 2025-07-22
 */
@Service
public class TagServiceImpl extends ServiceImpl<BookTagMapper, BookTag> implements TagService {

    @Override
    public IPage<BookTag> getTagList(Map<String, Object> params) {
        // 分页参数
        int current = Integer.parseInt(params.getOrDefault("current", "1").toString());
        int size = Integer.parseInt(params.getOrDefault("size", "10").toString());
        
        // 查询条件
        QueryWrapper<BookTag> queryWrapper = new QueryWrapper<>();
        
        // 名称搜索
        String name = (String) params.get("name");
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        
        // 按ID升序排序
        queryWrapper.orderByAsc("id");
        
        return this.page(new Page<>(current, size), queryWrapper);
    }

    @Override
    public List<BookTag> getAllTags() {
        QueryWrapper<BookTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("id");
        return this.list(queryWrapper);
    }

    @Override
    public boolean createTag(BookTag tag) {
        // 检查标签名称是否已存在
        if (isTagNameExists(tag.getName(), null)) {
            throw new RuntimeException("标签名称已存在");
        }
        
        // 设置默认颜色（如果未提供）
        if (StringUtils.isBlank(tag.getTagColor())) {
            tag.setTagColor("bg-blue-500");
        }
        
        return this.save(tag);
    }

    @Override
    public boolean updateTag(Integer tagId, BookTag tag) {
        // 检查标签名称是否已存在（排除当前标签）
        if (isTagNameExists(tag.getName(), tagId)) {
            throw new RuntimeException("标签名称已存在");
        }
        
        tag.setId(tagId);
        return this.updateById(tag);
    }

    @Override
    public boolean deleteTag(Integer tagId) {
        // TODO: 检查是否有图书使用了该标签
        // 这里可以添加检查book_tag_relation表的逻辑
        
        return this.removeById(tagId);
    }

    @Override
    public boolean isTagNameExists(String name, Integer excludeId) {
        QueryWrapper<BookTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        
        if (excludeId != null) {
            queryWrapper.ne("id", excludeId);
        }
        
        return this.count(queryWrapper) > 0;
    }
}
